<?php
namespace app\system\controller;


use app\common\model\HotSearchModel;
use think\Db;

class HotSearchController extends BaseController
{

    /**
     * 初始化
     */
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 热搜首页
     * @return mixed
     */
    public function index()
    {
        if($this->request->isAjax()){
            $data = $this->request->param();
            foreach($data['hot'] as $mid=>$search_titles){
                $info = Db::table('hot_search')->where('site_id',$this->getSiteId())->where('mid',$mid)->find();
                if($info){
                    Db::table('hot_search')->where('id',$info['id'])->setField('search_titles',$search_titles);
                }else{
                    Db::table('hot_search')->insert(['mid'=>$mid,'site_id'=>$this->getSiteId(),'search_titles'=>$search_titles]);
                }
            }
            $this->updateCache();
            $this->success('操作成功！');
        }
        $hot = Db::table('hot_search')->where('site_id',$this->getSiteId())->column('search_titles','mid');
        $moudleList = cache('cms_moudle');
        $this->assign('moudleList',$moudleList);
        $this->assign('hot',$hot);
        return $this->fetch();
    }

    /**
     * 更新缓存
     * @return bool
     */
    private function updateCache(){
        $list = Db::table('hot_search')->where('site_id',$this->getSiteId())->select();
        if($list->isEmpty()){
            return false;
        }else{
            $data=[];
            foreach($list as $v){
                $data[$v['mid']] = $v['search_titles'];
            }
            cache('hot_search'.$this->getSiteId(),$data);
        }
        return true;
    }
}
